package com.hcj.springcloud.ObserverPattern;

import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;

import java.util.Observable;
import java.util.Observer;

/**
 * jdk提供的观察者模式
 *
 * @author huangchangjin
 * @date 2024/7/6 11:04
 */
@Slf4j
public class JDKObserverPatternDemo {
    class MyObserver implements Observer {
        @Override
        public void update(Observable o, Object arg) {
            // 需要更新的逻辑
            log.info("Observable o.name = {} arg = {}", this.getClass().getSimpleName(), arg);
        }
    }

    class MyOtherObserver implements Observer {
        @Override
        public void update(Observable o, Object arg) {
            // 需要更新的逻辑
            log.info("Observable o.name = {} arg = {}", this.getClass().getSimpleName(), arg);
        }
    }

    class MyObserverable extends Observable {
        void doMyFunction(String noticeArg) {
            log.info("自定义函数");
            setChanged();
            notifyObservers(noticeArg);
        }
    }

    @Test
    void test() {
        MyObserver myObserver = new MyObserver();
        MyOtherObserver myOtherObserver = new MyOtherObserver();
        MyObserverable myObserverable = new MyObserverable();
        myObserverable.addObserver(myObserver);
        myObserverable.addObserver(myOtherObserver);

        myObserverable.doMyFunction("通知观察者。。。");
    }
}
